package io.wdb.modules.activity.wxapp.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.wdb.exchange.constant.EventEnum;
import com.wdb.exchange.constant.SourceEnum;
import com.wdb.exchange.model.Event;

import io.wdb.common.utils.CommonUtil;
import io.wdb.common.utils.ConstantConfig;
import io.wdb.common.utils.DateUtils;
import io.wdb.common.utils.UUIDGenerator;
import io.wdb.config.AmqpConfig;
import io.wdb.handler.AmqpSendHandler;
import io.wdb.modules.activity.wxapp.dao.HdConfigDao;
import io.wdb.modules.activity.wxapp.dao.HdLotteryUserInfoDao;
import io.wdb.modules.activity.wxapp.entity.HdConfigEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryActivityConvertInfoEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryUserCount;
import io.wdb.modules.activity.wxapp.entity.HdLotteryUserInfoEntity;
import io.wdb.modules.activity.wxapp.entity.LocationCountEntity;
import io.wdb.modules.activity.wxapp.service.HdLotteryUserInfoService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("hdLotteryUserInfoService")
public class HdLotteryUserInfoServiceImpl implements HdLotteryUserInfoService {
	private static final Logger logger = LoggerFactory.getLogger(HdLotteryUserInfoServiceImpl.class);
	@Autowired
	private HdLotteryUserInfoDao hdLotteryUserInfoDao;
	
	@Autowired
	private AmqpSendHandler amqpSendHandler;
	
	@Autowired
	private HdConfigDao hdConfigDao;
	
	@Override
	public HdLotteryUserInfoEntity queryObject(String id){
		return hdLotteryUserInfoDao.queryObject(id);
	}
	
	@Override
	public List<HdLotteryUserInfoEntity> queryList(Map<String, Object> map){
		return hdLotteryUserInfoDao.queryList(map);
	}
	
	public List<HdLotteryActivityConvertInfoEntity> listFriendsLottery(Map<String, Object> map){
		return hdLotteryUserInfoDao.listFriendsLottery(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return hdLotteryUserInfoDao.queryTotal(map);
	}
	
	@Override
	public String save(HdLotteryUserInfoEntity hdLotteryUserInfo){
		if(ObjectUtils.isEmpty(hdLotteryUserInfo.getId())) {
			hdLotteryUserInfo.setId(UUIDGenerator.getUUID());
			hdLotteryUserInfoDao.save(hdLotteryUserInfo);
		}else {
			hdLotteryUserInfoDao.update(hdLotteryUserInfo);
		}
		
		return hdLotteryUserInfo.getId();
		
	}
	
	@Override
	public void update(HdLotteryUserInfoEntity hdLotteryUserInfo){
		hdLotteryUserInfoDao.update(hdLotteryUserInfo);
	}
	
	@Override
	public void delete(String id){
		hdLotteryUserInfoDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		hdLotteryUserInfoDao.deleteBatch(ids);
	}
	
	/**
	 * 使用次数 lottery_status >= 0
	 * @param hdUserid
	 * @param userid
	 * @return
	 */
	public int usedLotteryCount(String hdUserid,String userid) {
		//查询当前用户当天抽奖次数
		Map<String, Object> map = new HashMap<String, Object>();
		List<HdLotteryUserInfoEntity>  hdLotteryUserInfoEntities = new ArrayList<HdLotteryUserInfoEntity>();
		if(ObjectUtils.isEmpty(userid)) {
			map.put("filterSql", " hd_user_id = '"+ hdUserid + "' AND lottery_status >= 0");
			hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		}else {
			map.put("filterSql", " (api_user_id = "+userid + " OR hd_user_id = '"+hdUserid + "')  AND lottery_status >= 0");
			hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		}
		int usedLotteryCount = 0;
		if(!ObjectUtils.isEmpty(hdLotteryUserInfoEntities)) {
			usedLotteryCount = hdLotteryUserInfoEntities.size();
		}
		return usedLotteryCount;
	}
	/**
	 * 查询当前用户当天之前由借阅还书产生抽奖次数
	 * @param hdUserid
	 * @return
	 */
	public int usedBorrowChance(String hdUserid) {
		String currentDate = DateUtils.format(new Date());// "yyyy-MM-dd"
		Map<String, Object> map = new HashMap<String, Object>();
		List<HdLotteryUserInfoEntity> hdLotteryUserInfoEntities = new ArrayList<HdLotteryUserInfoEntity>();
		map.put("filterSql", " hd_user_id = '" + hdUserid
				+ "' AND lottery_status >= 0 AND borrow_chance = 1 AND create_time < '" + currentDate + "'");
		hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		int usedBorrowChance = 0;
		if (!ObjectUtils.isEmpty(hdLotteryUserInfoEntities)) {
			usedBorrowChance = hdLotteryUserInfoEntities.size();
		}
		return usedBorrowChance;
	}
	
	/**
	 * 查询当前用户当天之前由借阅还书产生抽奖次数
	 * @param hdUserid
	 * @param userid
	 * @return
	 */
	public int currentBorrowChanceCount(String hdUserid,Long userid) {
		String currentDate = DateUtils.format(new Date());// "yyyy-MM-dd"
		Map<String, Object> map = new HashMap<String, Object>();
		List<HdLotteryUserInfoEntity> hdLotteryUserInfoEntities = new ArrayList<HdLotteryUserInfoEntity>();
		if(ObjectUtils.isEmpty(userid)) {
			map.put("filterSql", " hd_user_id = '"+ hdUserid + "' AND lottery_status >= 0 AND borrow_chance = 1 AND create_time >= '" + currentDate + "'" );
			hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		}else {
			map.put("filterSql", " (api_user_id = "+userid + " OR hd_user_id = '"+hdUserid + "')  AND lottery_status >= 0 AND borrow_chance = 1 AND create_time >= '" + currentDate + "'");
			hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		}
		hdLotteryUserInfoEntities = hdLotteryUserInfoDao.queryList(map);
		int currentBorrowChanceCount = 0;
		if (!ObjectUtils.isEmpty(hdLotteryUserInfoEntities)) {
			currentBorrowChanceCount = hdLotteryUserInfoEntities.size();
		}
		return currentBorrowChanceCount;
	}
	
	/**
	 * 分享增加的抽奖机会次数
	 * @param hdUserid
	 * @return
	 */
	public int parentShareLotteryCount(String hdUserid) {
		HdConfigEntity hdConfig = hdConfigDao.queryObject("shareMaxLimit");//最多25次分享
		 int shareMaxLimit = Integer.valueOf(hdConfig.getHdValue());
		// 查询当前用户当天抽奖次数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("hdUserId", hdUserid);
		List<HdLotteryUserCount> hdLotteryUserCounts = hdLotteryUserInfoDao.lotteryUserCount(map);
		int shareFriendsCount = 0;//分享给朋友 增加的次数统计
		for(HdLotteryUserCount hdLotteryUserCount : hdLotteryUserCounts) {
			if(ConstantConfig.NEW_USER_YES.equals(hdLotteryUserCount.getNewUser())) {
				shareFriendsCount += hdLotteryUserCount.getUserLotteryCount() * 2;
			}else {
				shareFriendsCount += hdLotteryUserCount.getUserLotteryCount() ;
			}
		}
		if(shareMaxLimit != 0 && shareFriendsCount > shareMaxLimit * 2) {
			shareFriendsCount = shareMaxLimit * 2;
		}
		return shareFriendsCount;
	}
	
	/**
	 * 发送优惠券
	 */
	public void sendLotteryAward(HdLotteryUserInfoEntity lotteryUserinfo, HdLotteryActivityEntity hdLotteryActivityEntity) {
		HdLotteryUserInfoEntity updateLotteryUserinfo = new HdLotteryUserInfoEntity();
		updateLotteryUserinfo.setId(lotteryUserinfo.getId());
		updateLotteryUserinfo.setBorrowChance(lotteryUserinfo.getBorrowChance());
		updateLotteryUserinfo.setApiUserId(lotteryUserinfo.getApiUserId());
		updateLotteryUserinfo.setUserStatus(ConstantConfig.LOTTERY_USER_STATUS_LOGINED);//已登录
		updateLotteryUserinfo.setModifyTime(new Date());
		updateLotteryUserinfo.setLotteryStatus(ConstantConfig.LOTTERY_STATUS_SENDED);//已发送
		//TODO 发送优惠券接口
		//判断奖品类型,目前只有奖券
		if(ConstantConfig.LOTTERY_AWARD_TYPE_NORMOL_COUPON.equals(hdLotteryActivityEntity.getType()) ||
				ConstantConfig.LOTTERY_AWARD_TYPE_BOOK_COUPON.equals(hdLotteryActivityEntity.getType())) {
			logger.info("send coupon interface:{}",hdLotteryActivityEntity.getLotteryCode());
			if(!CommonUtil.isEmpty(hdLotteryActivityEntity.getLotteryCode())) {
				Event event = new Event();
				event.userId = lotteryUserinfo.getApiUserId();
				event.source = SourceEnum.ACTIVITY;
				event.event = EventEnum.AWARD_PRESENT;
				event.extra = hdLotteryActivityEntity.getLotteryCode();
				event.eventTime = new Date().getTime();
				// 异步发送优惠券
				amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
			}
		}
		update(updateLotteryUserinfo);
	}
	
	/**
	 * 抽奖总数
	 */
	public List<LocationCountEntity>  locationCountAll(String hdActivityId){
		Map<String, Object> sql = new HashMap<>();
		sql.put("hdActivityId", hdActivityId);
		List<LocationCountEntity> all = hdLotteryUserInfoDao.locationCountAll(sql);
		
		return all;
	}
	/**
	 * 每人每个奖品抽奖数量
	 * @param hdLotteryActivityId
	 * @param hdUserId
	 * @return
	 */
	public List<LocationCountEntity>  lotteryLocationPerMan(String hdActivityId, String hdUserId){
		Map<String, Object> sql = new HashMap<>();
		sql.put("hdActivityId", hdActivityId);
		sql.put("hdUserid", hdUserId);
		List<LocationCountEntity> all = hdLotteryUserInfoDao.locationCountAll(sql);
		return all;
	}
	/**
	 * 当天奖品抽出数量
	 * @param hdLotteryActivityId
	 * @return
	 */
	public List<LocationCountEntity> lotteryLocationPerDay(String hdActivityId){
		Map<String, Object> sql = new HashMap<>();
		sql.put("hdActivityId", hdActivityId);
		sql.put("createTime", DateUtils.format(new Date()));
		List<LocationCountEntity> all = hdLotteryUserInfoDao.locationCountAll(sql);
		return all;
	}
	
}
